#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
飞书多维表格API接口全息遍历与智能决策系统 - 完整流水线启动脚本
直接调用现有的测试脚本，避免重复实现
"""

import sys
import os
import time
import subprocess
from pathlib import Path

def print_banner():
    """打印项目横幅"""
    print("=" * 80)
    print("                飞书多维表格接口全息遍历与智能决策系统")
    print("         Feishu Multidimensional Table API Test System")
    print("=" * 80)
    print("  版本: v1.0")
    print("  功能: 自动生成API测试用例，重点关注必填、唯一、长度约束")
    print("=" * 80)

def run_script(script_name, description):
    """
    运行指定的脚本
    
    Args:
        script_name: 脚本文件名
        description: 脚本描述
        
    Returns:
        是否成功
    """
    script_path = f"scripts/{script_name}"
    print(f"\n{description}")
    print(f"[执行] 运行脚本: {script_path}")
    print("-" * 60)
    
    try:
        # 直接执行脚本，不捕获输出
        result = subprocess.run([sys.executable, script_path])
        
        print("-" * 60)
        if result.returncode == 0:
            print(f"[成功] {description}")
            return True
        else:
            print(f"[失败] {description} (返回码: {result.returncode})")
            return False
            
    except Exception as e:
        print(f"[异常] {description}: {str(e)}")
        return False

def run_assertion_analysis():
    """
    运行断言分析
    
    Returns:
        是否成功
    """
    print(f"\n[第5步] 业务级自动断言分析")
    print(f"[执行] 运行断言分析: src/assert/assert.py")
    print("-" * 60)
    
    try:
        # 直接执行断言脚本，不捕获输出
        result = subprocess.run([sys.executable, "src/assert/assert.py"])
        
        print("-" * 60)
        if result.returncode == 0:
            print(f"[成功] 业务级自动断言分析完成")
            return True
        else:
            print(f"[失败] 断言分析失败 (返回码: {result.returncode})")
            return False
            
    except Exception as e:
        print(f"[异常] 断言分析: {str(e)}")
        return False

def main():
    """主流程"""
    print_banner()
    
    start_time = time.time()
    
    print("\n[开始] 执行完整流水线...")
    print("[步骤] 认证测试 -> 元数据获取 -> AI测试用例生成 -> CRUD测试执行 -> 断言分析")
    
    # 执行步骤
    steps = [
        ("test_auth.py", "[第1步] 飞书API认证测试"),
        ("test_metadata.py", "[第2步] 对象元数据获取和存储"),  
        ("build_rag_index.py", "[第3步] AI测试用例生成-构建rag索引"),
        ("rag_generate_invalid_values.py", "[第3步] AI测试用例生成-生成字段可能的异常值候选集"),  
        ("test_invalid_values.py", "[第3步] AI测试用例生成-测试异常值是否为真异常值并反馈清除"), 
        ("meta_data_parse.py", "[第3步] AI测试用例生成-生成带数据的测试用例"),
        ("generate_test_cases.py", "[第3步] AI测试用例生成-生成带描述和名称的测试用例"),
        
        ("test_curd.py", "[第4步] CRUD测试用例执行")
    ]
    
    success_count = 0
    
    # 执行前4步
    for script_name, description in steps:
        success = run_script(script_name, description)
        if success:
            success_count += 1
        else:
            print(f"\n[中断] 流水线中断，{description}失败")
            break
    
    # 如果前4步都成功，执行第5步断言分析
    if success_count == len(steps):
        print(f"\n[继续] 前{len(steps)}步执行成功，开始断言分析...")
        assertion_success = run_assertion_analysis()
        if assertion_success:
            success_count += 1
            print(f"\n[成功] 断言分析完成")
        else:
            print(f"\n[警告] 断言分析失败，但前{len(steps)}步已成功完成")
    
    # 结果汇总
    end_time = time.time()
    duration = end_time - start_time
    
    print("\n" + "="*80)
    if success_count >= len(steps):
        print("[完成] 完整流水线执行成功！")
        print(f"[统计] 完成步骤: {success_count}/{len(steps)+1} | 耗时: {duration:.2f}秒")
        print("[重点] 必填字段、唯一性约束、最大长度限制")
        if success_count == len(steps) + 1:
            print("[状态] 包含断言分析结果")
        else:
            print("[状态] 基础测试完成，断言分析失败")
    else:
        print("[失败] 流水线执行失败")
        print(f"[统计] 完成步骤: {success_count}/{len(steps)+1}")
        print("[建议] 请检查失败步骤的错误信息并修复配置")
    
    print("="*80)
    
    return success_count >= len(steps)

if __name__ == "__main__":
    try:
        success = main()
        sys.exit(0 if success else 1)
    except KeyboardInterrupt:
        print("\n\n[中断] 用户手动中断执行")
        sys.exit(1)
    except Exception as e:
        print(f"\n[错误] 执行过程出错: {str(e)}")
        sys.exit(1)